package HibernateMapping;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class User {

	int id;
	String idTwitter;
	String name;
	int followersCount;

	public static User getUser(String idUser, String userName) {
		Transaction trns = null;
		Session session = HibernateUtil.getSessionFactory().openSession();

		User user = null;

		try {
			trns = session.beginTransaction();
			user = (User) session
					.createQuery("from Keyword as k where k.id =:idUser")
					.setString("idUser", idUser).uniqueResult();

			if (!trns.wasCommitted())
				trns.commit();
		} catch (RuntimeException e) {
			if (trns != null) {
				trns.rollback();
			}
			e.printStackTrace();
		} finally {
			// session.flush();
			session.close();
		}

		if (user == null) {
			Transaction tms = null;
			Session session2 = HibernateUtil.getSessionFactory().openSession();

			User temp = new User();

			try {
				tms = session2.beginTransaction();

				temp.setIdTwitter(idUser);
				temp.setName(userName);
				session2.save(temp);
				if (!tms.wasCommitted())
					tms.commit();
			} catch (RuntimeException e) {
				if (tms != null) {
					tms.rollback();
				}
				e.printStackTrace();
			} finally {
				// session.flush();
				session2.close();
			}

			return temp;
		} else {
			return user;
		}
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getFollowersCount() {
		return followersCount;
	}

	public void setFollowersCount(int followersCount) {
		this.followersCount = followersCount;
	}

	public String getIdTwitter() {
		return idTwitter;
	}

	public void setIdTwitter(String idTwitter) {
		this.idTwitter = idTwitter;
	}

}
